package com.siyoumi.app.modules.app_ess.admin;

import com.siyoumi.app.entity.SysUser;
import com.siyoumi.app.modules.fun.service.SvcFun;
import com.siyoumi.app.modules.fun.vo.VaFunAdd;
import com.siyoumi.app.modules.fun.vo.VaFunRecordAdd;
import com.siyoumi.app.modules.user.service.SvcSysUser;
import com.siyoumi.component.XApp;
import com.siyoumi.config.SysConfig;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/app_ess/app_ess__fun__add")
public class app_ess__fun__add
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("导入");

        Map<String, Object> data = new HashMap<>();
        data.put("fgroup_order", 0);
        if (isAdminEdit()) {
        }
        getR().setData("data", data);
        setPageInfo("upload_file_size_max", SysConfig.getIns().getUploadFileSizeMax()); //上传大小

        return getR();
    }


    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public XReturn save(@Validated VaFunRecordAdd vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        if (vo.getFun() == 0) {
            result.addError(XValidator.getErr("fun", "不能输入0"));
        }
        XValidator.getResult(result);

        List<String> uidArr = XStr.arrToList(vo.getUids().split("\r\n"));
        if (uidArr.size() > 2000) {
            return EnumSys.ERR_VAL.getR("1次最多2000");
        }

        List<SysUser> listUser = SvcSysUser.getApp().get(uidArr);
        if (listUser.size() != uidArr.size()) {

            return EnumSys.ERR_VAL.getR("uid存在异常");
        }

        for (String uid : uidArr) {
            VaFunAdd funAddData = VaFunAdd.of(XApp.getUUID(), uid, uid, "fun", vo.getFun(), vo.getDesc());
            funAddData.setUpdate_fun(true);
            SvcFun.getBean().add(funAddData);
        }

        return XReturn.getR(0);
    }
}
